<template>
    <div class="upload-file">
        <div v-if="format" class="styleDisplay">
            <div v-for="(fit, index) in fileList" :key="fit" class="styleDisplays">
                <el-image class="preview" style="width: 320px; height: 244px;" :src="fit.url" fit="fill" />
                <el-image class="delete" :src="icon_shanchu" @click="handleDelete(index)"></el-image>
                <el-image class="quanping" :src="icon_quanping" @click="handlePictureCardPreview(fit)"></el-image>

                <div class="download" @click="downloads(fit)">
                    <el-image class="downloadpic" :src="icon_xiazai"></el-image>
                    <span class="downloadtitle">下载图片</span>
                </div>
            </div>
        </div>
        <el-upload multiple action="#" :before-upload="handleBeforeUpload" :file-list="fileList" :limit="limit" v-if="fileList.length !== limit"
            v-loading.lock="isLoading" :on-error="handleUploadError" :on-exceed="handleExceed"
            :on-success="handleUploadSuccess" :show-file-list="false" :headers="headers" class="upload-file-uploader"
            ref="fileUploadRef" drag :http-request="httpRequest">
            <!-- 上传按钮 -->
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
                将文件拖到此处，或 <em>点击上传</em>
            </div>
        </el-upload>
        <!-- 上传提示 -->
        <div class="el-upload__tip" v-if="showTip && fileList.length !== limit">
            请上传
            <template v-if="fileSize">
                大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b>
            </template>
            <template v-if="fileType">
                格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b>
            </template>
            的文件
        </div>

        <!-- 文件列表 -->
        <transition-group v-if="!format" class="upload-file-list el-upload-list el-upload-list--text"
            name="el-fade-in-linear" tag="ul">
            <li :key="file.uid" class="el-upload-list__item ele-upload-list__item-content"
                v-for="(file, index) in fileList">
                <el-link :href="`${file.url}`" :underline="false" target="_blank">
                    <span class="el-icon-document"> {{ file.name }} </span>
                </el-link>
                <div class="ele-upload-list__item-content-action">
                    <el-link :underline="false" @click="handleDelete(index)" type="danger">删除</el-link>
                </div>
            </li>
        </transition-group>

        <el-dialog v-model="dialogVisible" title="预览" width="800px" append-to-body>
            <img :src="dialogImageUrl" style="display: block; max-width: 100%; margin: 0 auto" />
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { propTypes } from '@/utils/propTypes';
import { globalHeaders } from "@/utils/request";
import icon_shanchu from '@/assets/images/icon_shanchu.png'
import icon_quanping from '@/assets/images/icon_quanping.png'
import icon_xiazai from '@/assets/images/icon_xiazai.png'
import * as OSS from 'ali-oss';
import { put, getFileNameUUID } from '@/utils/oss'

const props = defineProps({
    modelValue: [String, Object, Array],
    // 数量限制
    limit: propTypes.number.def(5),
    // 大小限制(MB)
    fileSize: propTypes.number.def(30),
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: propTypes.array.def(['png', 'jpg', 'jpeg']),
    // 是否显示提示
    isShowTip: propTypes.bool.def(true),
    // 是否图片格式的拖拽
    format: propTypes.bool.def(false),
    // 传回的文件名字
    filename: propTypes.string.def(""),
});

const isLoading = ref()
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const emit = defineEmits(['update:modelValue', 'modelValueName', 'modelValueSize']);
const number = ref(0);
const uploadList = ref<any[]>([]);

const baseUrl = import.meta.env.VITE_APP_BASE_API;
const headers = ref(globalHeaders());

const fileList = ref<any[]>([]);
const showTip = computed(
    () => props.isShowTip && (props.fileType || props.fileSize)
);

const dialogImageUrl = ref('');
const dialogVisible = ref(false);

const today = new Date();
const year = today.getFullYear();
const month = today.getMonth() + 1;
const date = today.getDate();

const fileUploadRef = ref<ElUploadInstance>();
// 有数据的回显
watch(
    () => props.filename,
    async (val) => {
        if (val) {
            // 然后将数组转为对象数组
            fileList.value = [{ name: props.filename, url: import.meta.env.VITE_APP_PIC_URL + props.modelValue }]
        } else {
            fileList.value = [];
            return [];
        }
    },
    { deep: true, immediate: true }
);


const httpRequest = (option: any) => {
    // 获取文件的后缀名
    // let objName = getFileNameUUID()
    var obj = option.file.name
    var index = obj.lastIndexOf(".");
    obj = obj.substring(index, obj.length);
    // 生成的文件名，保留文件后缀名，进行拼接      
    let objName = getFileName(option.file.name)
    const data = year + '/' + month + '/' + date
    // 调用 ali-oss 中的方法,flieName是存放的文件夹名称，可自己定义
    put(`${data}/${getFileNameUUID()}/${objName}`, option.file).then(res => {
        fileList.value.push({ name: objName, url: res.url })
        emit("update:modelValue", getPicByfullPath(fileList.value));
        emit("modelValueName", objName);
        emit("modelValueSize", (option.file.size / 1024 / 1024).toFixed(1));
        // proxy?.$modal.closeLoading();
        isLoading.value = false
    }).catch(error => {
        isLoading.value = false
    })

}

// 上传前校检格式和大小
const handleBeforeUpload = (file: any) => {
    // 校检文件类型
    if (props.fileType.length) {
        const fileName = file.name.split('.');
        const fileExt = fileName[fileName.length - 1];
        const isTypeOk = props.fileType.indexOf(fileExt) >= 0;
        if (!isTypeOk) {
            proxy?.$modal.msgError(`文件格式不正确, 请上传${props.fileType.join("/")}格式文件!`);
            return false;
        }
    }
    // 校检文件大小
    if (props.fileSize) {
        const isLt = file.size / 1024 / 1024 <= props.fileSize;
        if (!isLt) {
            proxy?.$modal.msgError(`上传文件大小不能超过 ${props.fileSize} MB!`);
            return false;
        }
    }
    // 名字校验
    console.log(props)
    // proxy?.$modal.loading("正在上传文件，请稍候...");
    isLoading.value = true
    number.value++;
    return true;
}
// 图片全路径转成半路径
const getPicByfullPath = (list: any[]) => {
    if (list.length > 0) {
        const updatedList = list.map((item: any) => {
            return item.url.split(import.meta.env.VITE_APP_PIC_URL)[1];
        });
        return updatedList.join(',');
    } else {
        return '';
    }
}

// 文件个数超出
const handleExceed = () => {
    proxy?.$modal.msgError(`上传文件数量不能超过 ${props.limit} 个!`);
}

// 上传失败
const handleUploadError = () => {
    proxy?.$modal.msgError("上传文件失败");
}

// 上传成功回调
const handleUploadSuccess = (res: any, file: UploadFile) => {
    if (res.code === 200) {
        uploadList.value.push({ name: res.data.fileName, url: res.data.url, ossId: res.data.ossId, size: (file.size / 1024 / 1024).toFixed(1) });
        uploadedSuccessfully();
    } else {
        number.value--;
        // proxy?.$modal.closeLoading();
        isLoading.value = false
        proxy?.$modal.msgError(res.msg);
        fileUploadRef.value?.handleRemove(file);
        uploadedSuccessfully();
    }
}

// 删除文件
const handleDelete = (index: number) => {
    fileUploadRef.value?.handleRemove(fileList.value[index])
    fileList.value.splice(index, 1);
    emit("update:modelValue", listToString(fileList.value));
    emit("modelValueName", listToStringName(fileList.value));
    emit("modelValueSize", listToStringSize(fileList.value));
}

// 上传结束处理
const uploadedSuccessfully = () => {
    if (number.value > 0 && uploadList.value.length === number.value) {
        fileList.value = fileList.value.filter(f => f.url !== undefined).concat(uploadList.value);
        uploadList.value = [];
        number.value = 0;
        emit("update:modelValue", listToString(fileList.value));
        emit("modelValueName", listToStringName(fileList.value));
        emit("modelValueSize", listToStringSize(fileList.value));
        // proxy?.$modal.closeLoading();
        isLoading.value = false
    }
}

// 获取文件名称
const getFileName = (name: string) => {
    // 如果是url那么取最后的名字 如果不是直接返回
    if (name.lastIndexOf("/") > -1) {
        return name.slice(name.lastIndexOf("/") + 1);
    } else {
        return name;
    }
}

// 对象转成指定字符串分隔
const listToString = (list: any[], separator?: string) => {
    let strs = "";
    separator = separator || ",";
    list.forEach(item => {
        if (item.ossId) {
            strs += item.ossId + separator;
        }
    })
    return strs != "" ? strs.substring(0, strs.length - 1) : "";
}
// 对象转成指定字符串分隔名称
const listToStringName = (list: any[], separator?: string) => {
    let strs = "";
    separator = separator || ",";
    list.forEach(item => {
        if (item.ossId) {
            strs += item.name + separator;
        }
    })
    return strs != "" ? strs.substring(0, strs.length - 1) : "";
}
const listToStringSize = (list: any[], separator?: string) => {
    let strs = "";
    separator = separator || ",";
    list.forEach(item => {
        if (item.ossId) {
            strs += item.size + separator;
        }
    })
    return strs != "" ? strs.substring(0, strs.length - 1) : "";
}

// 预览
const handlePictureCardPreview = (file: any) => {
    if (isPdf(file)) {
        window.open(import.meta.env.VITE_APP_PREVIEW_URL + file.url.split(import.meta.env.VITE_APP_PIC_URL)[1], '_blank');
    } else {
        dialogImageUrl.value = file.url;
        dialogVisible.value = true;
    }
}
const isPdf = (fit: any) => {
    return fit.name.includes(".pdf")
}
/** 下载 */
const downloads = async (imgUrl: any) => {
    const response = await fetch(imgUrl.url)
    const blob = await response.blob()
    // 创建下载链接
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = imgUrl.name
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    // 释放 Blob URL
    window.URL.revokeObjectURL(url)
}
</script>

<style scoped lang="scss">
.upload-file{
    width: 300px;
}
.el-upload-list{
    margin: 0px 0 0 !important;
}
.upload-file-uploader {
    margin-bottom: 5px;
}

.upload-file-list .el-upload-list__item {
    border: 1px solid #e4e7ed;
    line-height: 2;
    margin-bottom: 10px;
    position: relative;
}

.upload-file-list .ele-upload-list__item-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: inherit;
}

.ele-upload-list__item-content-action .el-link {
    margin-right: 10px;
}

.styleDisplay {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
}

.styleDisplays {
    margin: 10px 0;
    position: relative;
    height: 264px;

    .preview {
        border-radius: 5px;
        border: 1px dashed #AFB6C3;
    }

    .delete {
        position: absolute;
        right: 5px;
        top: 5px;
        z-index: 5;
        width: 20px;
        height: 20px;
        cursor: pointer;
    }

    .quanping {
        position: absolute;
        right: 5px;
        bottom: 25px;
        z-index: 5;
        width: 20px;
        height: 20px;
        cursor: pointer;
    }

    .download {
        position: absolute;
        width: 100%;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;

        .downloadpic {
            width: 14px;
            height: 14px;
        }

        .downloadtitle {
            color: #0094FF;
            font-size: 14px;
        }
    }
}
</style>